package com.bcu.cn.onlineexamsystem.user.service;

import com.bcu.cn.onlineexamsystem.user.entity.Course;
import com.bcu.cn.onlineexamsystem.user.entity.Score;
import com.bcu.cn.onlineexamsystem.user.entity.Ranking;
import com.bcu.cn.onlineexamsystem.Repository.CourseRepository;
import com.bcu.cn.onlineexamsystem.Repository.ScoreRepository;
import com.bcu.cn.onlineexamsystem.Repository.RankingRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class TeacherService {

    @Autowired
    private ScoreRepository scoreRepository;

    @Autowired
    private CourseRepository courseRepository;

    @Autowired
    private RankingRepository rankingRepository;

    // 教师录入成绩
    @Transactional
    public boolean addScore(Score score, String teacherId) {
        // 校验课程是否存在
        Course course = courseRepository.findByTeacherId(teacherId).stream()
                .filter(c -> c.getCourseId().equals(score.getCourseId()))
                .findFirst()
                .orElse(null);
        if (course == null) {
            return false; // 无权限操作该课程
        }

        // 校验成绩是否已存在
        if (scoreRepository.findByCourseIdAndStudentId(score.getCourseId(), score.getStudentId()) != null) {
            return false; // 成绩已存在
        }

        score.setTeacherId(teacherId);
        score.setSubmitTime(LocalDateTime.now());
        scoreRepository.save(score);

        // 更新排名
        updateRanking(score.getCourseId());
        return true;
    }

    // 更新课程排名
    public void updateRanking(String courseId) {
        List<Score> scores = scoreRepository.findByCourseId(courseId);
        scores.sort((s1, s2) -> Double.compare(s2.getScore(), s1.getScore()));
        for (int i = 0; i < scores.size(); i++) {
            Ranking ranking = new Ranking();
            ranking.setStudentId(scores.get(i).getStudentId());
            ranking.setCourseId(courseId);
            ranking.setRank(i + 1);
            ranking.setUpdateTime(LocalDateTime.now());
            rankingRepository.save(ranking);
        }
    }

    // 导出成绩报表（示例）
    public List<Score> exportScores(String courseId) {
        return scoreRepository.findByCourseId(courseId);
    }
}